//
//  AppDelegate.m
//  RunningMan
//
//  Created by 姜勇利 on 16/5/18.
//  Copyright © 2016年 JohnnyB. All rights reserved.
//

#import "AppDelegate.h"
#import "EMSDK.h"
#import "JoLoginViewController.h"
#import <RongIMKit/RongIMKit.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
// 腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
//微信SDK头文件
#import "WXApi.h"
//新浪微博SDK头文件
#import "WeiboSDK.h"
//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"

//人人SDK头文件
#import <RennSDK/RennSDK.h>

#import "CoreDataManager.h"

#import "ViewController.h"

#import <BmobSDK/Bmob.h>

#import "LTIntroductionViewController.h"

@interface AppDelegate ()<RCIMUserInfoDataSource>

@property (nonatomic, retain) LTIntroductionViewController *firstLog;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    NSString *firstLog = [[NSUserDefaults standardUserDefaults] objectForKey:@"firstlog"];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        NSLog(@"第一次启动");
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        //如果是第一次登陆
        if (![firstLog isEqualToString:@"YES"]) {
        NSArray *main = @[@"2aFYm.jpeg",@"uvhj4.t.jpeg",@"KNBkj.jpeg"];
        NSArray *back = @[@"2aFYm.jpeg",@"uvhj4.t.jpeg",@"KNBkj.jpeg"];
        self.firstLog = [[LTIntroductionViewController alloc]initWithCoverImageNames:main backgroundImageNames:back];
        [self.window makeKeyAndVisible];
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UITabBarController *tabVc = [story instantiateViewControllerWithIdentifier:@"tabBar"];
            self.window.rootViewController = tabVc;
        self.window.rootViewController = tabVc;
        [self.window addSubview:self.firstLog.view];
        [self.window bringSubviewToFront:self.firstLog.view];
        //记录状态
        [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"firstlog"];
        }
    }else{
        NSLog(@"不是第一次启动");
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UITabBarController *tabVc = [story instantiateViewControllerWithIdentifier:@"tabBar"];
        self.window.rootViewController = tabVc;
    }
    //点击button
    __weak typeof(self)weakself = self;
    weakself.firstLog.didSelectedEnter = ^(){
        [weakself.firstLog.view removeFromSuperview];
        weakself.firstLog.view = nil;
    };
    sleep(2);

    //AppKey:注册的AppKey，详细见下面注释。
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    EMOptions *options = [EMOptions optionsWithAppkey:@"666-666#running"];
    options.apnsCertName = @"RunningMan_R";
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    // Override point for customization after application launch.
    
    [[RCIM sharedRCIM] initWithAppKey:@"sfci50a7cv3mi"];
    [[RCIM sharedRCIM] connectWithToken:@"1LCtubG8HXmgsF1fcBNtombR9GaA0BUVOZjrLVnSB1NwCAELF4ThZ337w4BtcfsnnuBuMrnySq5urqVLBm5s9Q==" success:^(NSString *userId) {
        
        //设置代理人.
        [[RCIM sharedRCIM] setUserInfoDataSource:self];
        
        NSLog(@"登录成功,当前登录的ID:%@", userId);
        
    } error:^(RCConnectErrorCode status) {
        
        NSLog(@"登录失败,错误码%ld",(long)status);
        
    } tokenIncorrect:^{
        
        NSLog(@"Token错误!");
    }];
    
// shareSDK
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    
    
    [ShareSDK registerApp:@"RunningMan_R"
     
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeMail),
                            @(SSDKPlatformTypeSMS),
                            @(SSDKPlatformTypeCopy),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformTypeRenren),
                            @(SSDKPlatformTypeGooglePlus)]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             case SSDKPlatformTypeRenren:
                 [ShareSDKConnector connectRenren:[RennClient class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"2546813338"
                                           appSecret:@"54a42b5090f761af7dba63c51aff191d"
                                         redirectUri:@"www.test.com"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx4d5895f58cf16b23"
                                       appSecret:@"f68fc197667e1d9003e0782ef5d98ae8"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1105419596"
                                      appKey:@"Nz5Ruxbn3uRI6Agp"
                                    authType:SSDKAuthTypeWeb];
                 break;
             default:
                 break;
         }
     }];
  // 新浪微博的外部库如果不要客户端分享或者不需要加关注微博的功能可以不添加，否则要添加，QQ，微信，google＋这些外部库文件必须要加
    
    [Bmob registerWithAppKey:@"e629eae24e68e250e4262ea435b37896"];
    
    return YES;
}

- (void)getUserInfoWithUserId:(NSString *)userId
                   completion:(void (^)(RCUserInfo *userInfo))completion {
    
    if ([userId isEqualToString:@"test"]) {
        
        RCUserInfo *usetInfo = [[RCUserInfo alloc]init];
        usetInfo.userId = userId;
        usetInfo.name = @"测试";
        usetInfo.portraitUri = @"http://pic1.nipic.com/2008-11-13/2008111384358912_2.jpg";
        return completion(usetInfo);
    }
    
    return completion(nil);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}


// App进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    
    [[EMClient sharedClient] applicationDidEnterBackground:application];
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [ViewController pauseGame];
}

// App将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [[EMClient sharedClient] applicationWillEnterForeground:application];
    
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    
    // 出现意外退出保存
    [[CoreDataManager shareManager]saveContext];
    
    [ViewController pauseGame];
}

@end
